// Config file for running Rollup in "normal" mode (non-watch)
// ----------------------------------------------------------------------------
import path from "path";
import copy from "rollup-plugin-copy";
import json from "@rollup/plugin-json";
import replace from "@rollup/plugin-replace";
import commonjs from "@rollup/plugin-commonjs";
import typescript from "@rollup/plugin-typescript";
import nodeResolve from "@rollup/plugin-node-resolve";
import terser from "@rollup/plugin-terser";
import { readFileSync } from "fs";
// ----------------------------------------------------------------------------
/** 根目录 */
const root = process.cwd();
/** 编译环境 {development, production} */
const node_env = process.env.NODE_ENV;
const production = node_env === "production";
/** 模块路径 (在 package.json 中的自定义) */
const modulePath = process.env.modulePath;
/** 输入文件 index.ts (在 package.json 中的自定义) */
const inputFile = process.env.inputFile;
/** 扩展 */
const extend = process.env.extend;
/** 当前日期 */
const currentDate = new Date();
/** package.json */
const pkg = JSON.parse(readFileSync(new URL("./package.json", import.meta.url), "utf8"));
// ----------------------------------------------------------------------------
/**
 * bundle type
 */
const BundleType = {
    /**
     * AMD - 异步模块规范, 适用于 RequireJS 等模块加载器, 用于浏览器端
     */
    AMD: "amd",
    /**
     * CJS - CommonJS, 适用于 Node 环境和其他打包工具
     */
    CJS: "cjs",
    /**
     * ESM - 是 es 模块文件，适用于其他打包工具，支持 <script type=module> 标签的浏览器
     */
    ESM: "esm",
    /**
     * UMD - 通用模块规范，同时支持 amd，cjs 和 iife, , 适用于 RequireJS 等模块加载器, 用于浏览器端
     */
    UMD: "umd",
    /**
     * IIFE - 自执行函数，适用于 <script> 标签（如果你想为你的应用程序创建 bundle，那么你可能会使用它）
     */
    IIFE: "iife",
    /**
     * SYSTEM - SystemJS 模块加载器的原生格式（别名：systemjs）
     */
    SYSTEM: "system"
};
// ----------------------------------------------------------------------------
const banner = `/**
 * @name        ${pkg.name}
 * @verions     ${pkg.version}
 * @author      ${pkg.author.name}
 * @email       ${pkg.author.email}
 * @license     ${pkg.license}
 * @buildtime   __buildDate__
 * @copyright   Copy right (c) 2020 - ${currentDate.getFullYear()}. All rights reserved.
 *
******************************************************************************/`;
// ----------------------------------------------------------------------------
const outputCommon = {
    banner: banner,
    compact: false,
    sourcemap: true, // boolean | 'inline' | 'hidden'
    sourcemapExcludeSources: true // 源代码是否添加到 sourcemap 文件中
    // footer: footer,
};
// ----------------------------------------------------------------------------
/** 输出目录 */
const outDir = "dist";
const outFname = "index";
// ----------------------------------------------------------------------------
const bundle_amd = `${outDir}/${outFname}.amd.js`;
const bundle_cjs = `${outDir}/${outFname}.cjs.js`;
const bundle_esm = `${outDir}/${outFname}.esm.js`;
const bundle_umd = `${outDir}/${outFname}.umd.js`;
const bundle_iife = `${outDir}/${outFname}.iife.js`;
const bundle_system = `${outDir}/${outFname}.system.js`;
// ----------------------------------------------------------------------------
// 在 package.json 定义: ["main", "module", "commonjs", "unpkg"],
const bundle_main = pkg.main;
const bundle_module = pkg.module;
const bundle_commonjs = pkg.commonjs;
const bundle_unpkg = pkg.unpkg;
// ----------------------------------------------------------------------------
const Input = path.resolve(root, inputFile);

const Output = [
    // all BundleType
    buildBundle(bundle_amd, BundleType.AMD, production),
    buildBundle(bundle_cjs, BundleType.CJS, production),
    buildBundle(bundle_esm, BundleType.ESM, production),
    buildBundle(bundle_umd, BundleType.UMD, production),
    buildBundle(bundle_iife, BundleType.IIFE, production),
    buildBundle(bundle_system, BundleType.SYSTEM, production),
    buildBundle(bundle_unpkg, BundleType.UMD, true),
    // package.json define
    buildBundle(bundle_main, BundleType.UMD, production),
    buildBundle(bundle_module, BundleType.ESM, production),
    buildBundle(bundle_commonjs, BundleType.CJS, production)
];

const Plugins = [
    json(),
    commonjs({
        include: "node_modules/**"
    }),
    typescript({
        cacheDir: "cache",
        outputToFilesystem: true,
        tsconfig: path.resolve(root, "tsconfig.json")
    }),
    nodeResolve({
        browser: true,
        mainFields: ["main", "module", "commonjs", "unpkg"],
        extensions: [".mjs", ".js", ".json", ".node", ".jsx", ".ts", ".tsx"],
        preferBuiltins: true
    }),
    replace({
        preventAssignment: true,
        __buildDate__: () => new Date().toString() // e.g. toLocaleDateString("af" | "en" | "zh-cn")
    }),
    copy({
        targets: [
            { src: ["src/types/**/*.d.ts"], dest: "dist/types" },
            // { src: ["package.json"], dest: "dist" },
            { src: ["dist"], dest: "example", rename: "mylibs" },
            { src: ["public"], dest: "example", rename: "assets" },
            { src: ["thirdParty"], dest: "example", rename: "libs" }
        ],
        copyOnce: false,
        verbose: true // 显示复制的文件信息到输出窗口
    })
];
// ----------------------------------------------------------------------------
/**
 * @function  生成 rollup.output bundle 配置
 * @param {string} filePath 用于指定生成的 bundle 文件 <br>
 * @param {string} formating 用于指定生成的 bundle 的格式 ["amd", "cjs", "esm", "umd", "iife", "system"] <br>
 * @param {boolean} minify 压缩代码 <br>
 * @returns
 * <p>
 * amd    – 异步模块加载，适用于 RequireJS 等模块加载器, 用于浏览器端
 * cjs    – CommonJS，适用于 Node 环境和其他打包工具（别名：commonjs）
 * esm    – 将 bundle 保留为 ES 模块文件，适用于其他打包工具，以及支持 <script type=module> 标签的浏览器。（别名：es, esm, module）
 * umd    – 通用模块定义规范，同时支持 amd, cjs 和 iife
 * iife   – 自执行函数，适用于 <script> 标签（如果你想为你的应用程序创建 bundle，那么你可能会使用它）
 * system – SystemJS 模块加载器的原生格式（别名：systemjs）
 * </p>
 */
function buildBundle(filePath, formating, minify = false) {
    const temp = {
        file: filePath,
        format: `${formating}`,
        name: `${formating}.namespace`,
        ...outputCommon,
        // 插件
        plugins: []
    };

    if (minify) {
        temp.plugins.push(terser()); // 压缩代码
    }

    return temp;
}

/**
 * 显示环境变量
 */
function display_env() {
    console.log(`root = ${root}`);
    console.log(`NODE_ENV = ${node_env}`);
    console.log(`modulePath = ${modulePath}`);
    console.log(`inputFile = ${inputFile}`);
    console.log(`extend = ${extend}`);
}

// ----------------------------------------------------------------------------
export { banner, Input, Output, Plugins, display_env };
// ----------------------------------------------------------------------------
